package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import controllers.PartManagementController;

public class MenuBar extends JMenuBar {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JMenu fileMenu;
	private JMenuItem exitItem;
	private JMenuItem openItem;
	private JMenuItem saveAsItem;
	private JMenuItem saveItem;
	
	public MenuBar() {
		init();
	}
	
	private void closeItemClicked() {
		System.exit(0);
	}
	
	private void openItemClicked() {
		JFileChooser chooser = new JFileChooser();
		chooser.setFileFilter(new FileNameExtensionFilter("Parts Data Files", "dat"));
		if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			String file = chooser.getSelectedFile().getAbsolutePath();
			if (!PartManagementController.getInstance().openPartFile(file)) {
				JOptionPane.showMessageDialog(this, "Could not open file " + file, "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private void saveAsItemClicked() {
		JFileChooser chooser = new JFileChooser();
		chooser.setFileFilter(new FileNameExtensionFilter("Parts Data Files", "dat"));
		if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
			String file = chooser.getSelectedFile().getAbsolutePath();
			PartManagementController.getInstance().savePartFileAs(file);
		}
	}
	
	private void saveItemClicked() {
		
	}
	
	private void init() {
		fileMenu = new JMenu("File");
		exitItem = new JMenuItem("Exit");
		exitItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				closeItemClicked();
			}
		});
		openItem = new JMenuItem("Open File...");
		openItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				openItemClicked();
			}
		});
		saveAsItem = new JMenuItem("Save As...");
		saveAsItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				saveAsItemClicked();
			}
		});
		saveItem = new JMenuItem("Save");
		saveItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				saveItemClicked();				
			}
		});
		
		fileMenu.add(openItem);
		fileMenu.add(saveAsItem);
		fileMenu.add(saveItem);
		fileMenu.add(exitItem);		
		this.add(fileMenu);
	}
}
